package com.ubi.core.database;

import com.ubi.core.utils.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.List;

public class JDBCAccess {

    private final Logger logger = LoggerFactory.getLogger(JDBCAccess.class);

    private JdbcTemplate jdbcTemplate;

    public int[] batchExecute(String sql, List<Object[]> params) {
        StopWatch watch = new StopWatch();
        int totalUpdatedRows = 0;
        try {

            int[] results = jdbcTemplate.batchUpdate(sql, params);
            for (int updatedRows : results) {
                totalUpdatedRows += updatedRows;
            }
            return results;
        } finally {
            logger.debug("batchExecute, sql={}, params={}, totalUpdatedRows={}, elapsedTime={}", sql, params, totalUpdatedRows, watch.elapsedTime());
        }
    }

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
}
